//
//  ViewController.m
//  OCR
//
//  Created by huawei on 2018/10/31.
//  Copyright © 2018/10/31 huawei. All rights reserved.
//

/*
 * sdk reference linking：https://support.huaweicloud.com/sdkreference-ocr/ocr_04_0016.html
 */


#import "ViewController.h"
#import "HWOcrClientAKSK.h"
#import "HWOcrClientToken.h"
#import "IdCardItem.h"
#import "VatInvoiceItem.h"
#import "SW_OCRCaptureViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *uriLabel;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UITextView *resultTextView;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageView.userInteractionEnabled =YES;
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ss)]];
//    [self tokenOcrService];
    
//    [self akskOcrService];

//    [self tokenAutoClassificationService];
}

- (void)ss {
    SW_OCRCaptureViewController *ss = [[SW_OCRCaptureViewController alloc] init];
    ss.imageblock = ^(UIImage * _Nonnull image) {
        self.imageView.image =image;
    };
    ss.direction =CameraDirectionHorizontal;
    [self presentViewController:ss animated:YES completion:^{
        [self akskOcrService];
    }];
    
}


- (void)tokenOcrService{
# warning Set required parameters
    NSString *domainName = @"xxx";// if the user isn't IAM user, domain_name is the same with username
    NSString *userName = @"xxx";
    NSString *password = @"xxx";
    NSString *region = @"cn-north-4";
    NSString *uri = @"/v1.0/ocr/id-card";
    UIImage *image = [UIImage imageNamed:@"id-card-demo"];
    
    self.uriLabel.text = uri;
    self.imageView.image = image;
    
    // initialize HWOcrClientToken
    HWOcrClientToken *token = [[HWOcrClientToken alloc] initWithDomainName:domainName userName:userName password:password region:region];
    NSDictionary *option = @{};
    // NSDictionary *option = @{@"side" : @"front"};
    // NSDictionary *option = @{@"url" : @"https://obs-soy.obs.cn-north-4.myhuaweicloud.com/xxx.png"};

    // request ocr service
    __weak typeof(self) weakSelf = self;
    [token requestOcrServiceWithUri:uri image:image options:option
                     successHandler:^(id result) {
                         NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:nil];
                         NSLog(@"resultDict = %@", resultDict);
                         dispatch_async(dispatch_get_main_queue(), ^{
                             NSString *jsonStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
                             weakSelf.resultTextView.text = jsonStr;
                         });
                     } failHandler:^(NSError *errMsg, NSInteger errCode) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             weakSelf.resultTextView.text = @"recognise error";
                         });
                     }];
    
}
- (void)akskOcrService{
# warning Set required parameters
    NSString *AK = @"SJPUJHRR5IUMG2UCTGYD";// AK from authentication
    NSString *SK = @"wBE72mkfxgMJ7ntosdpU34oRhtAKZsjfNtMjtVFV";// SK from authentication
    NSString *region = @"cn-north-4";// http endpoint information
    NSString *uri = @"/v1.0/ocr/id-card";
    UIImage *image = self.imageView.image?:[UIImage imageNamed:@"id-card-demo"];
    
    self.uriLabel.text = uri;
//    self.imageView.image = image;
    // initialize HWOcrClientAKSK from ak,sk and endpoint information
    HWOcrClientAKSK *aksk = [[HWOcrClientAKSK alloc] initWithAppKey:AK AppSecretKey:SK region:region];
    NSDictionary *option = @{};
    // NSDictionary *option = @{@"side" : @"front"};
    // NSDictionary *option = @{@"url" : @"https://obs-soy.obs.cn-north-4.myhuaweicloud.com/xxx.png"};

    __weak typeof(self) weakSelf = self;
    // request ocr service
    [aksk requestOcrServiceWithUri:uri image:image options:option
                    successHandler:^(id result) {
                        NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:nil];
                        NSLog(@"resultDict = %@", resultDict);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSString *jsonStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
                            weakSelf.resultTextView.text = jsonStr;
                        });
                    } failHandler:^(NSError *error, NSInteger errCode) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            weakSelf.resultTextView.text = @"recognise error";
                        });
                    }];
    
}

- (void)tokenAutoClassificationService{
# warning Set required parameters
    NSString *domainName = @"xxx";// if the user isn't IAM user, domain_name is the same with username
    NSString *userName = @"xxx";
    NSString *password = @"xxx";
    NSString *region = @"cn-north-4";
    NSString *uri = @"/v1.0/ocr/auto-classification";
    UIImage *image = [UIImage imageNamed:@"vat-invoice-demo"];

    self.uriLabel.text = uri;
    self.imageView.image = image;

    // initialize HWOcrClientToken
    HWOcrClientToken *token = [[HWOcrClientToken alloc] initWithDomainName:domainName userName:userName password:password region:region];

    NSDictionary *options = @{@"type_list" : @[@"vat_invoice", @"id_card_protrait_side"]};

    // request ocr service
    __weak typeof(self) weakSelf = self;
    [token requestOcrServiceWithUri:uri image:image options:options successHandler:^(id result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *jsonStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
            weakSelf.resultTextView.text = jsonStr;
        });
        NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"resultDict = %@", resultDict);

        NSString *error_code = resultDict[@"error_code"];
        if (error_code.length == 0) {
            [self decodeResponse:resultDict];
        } else {
            NSString *error_msg = resultDict[@"error_msg"];
            NSLog(@"error_code = %@\nerror_msg = %@", error_code, error_msg);
        }
    } failHandler:^(NSError *errMsg, NSInteger errCode) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.resultTextView.text = @"recognise error";
        });
    }];
}

- (void)decodeResponse:(NSDictionary *)resultDict {
    NSArray *resultArr = resultDict[@"result"];
    for (NSDictionary *item in resultArr) {
        NSString *type = item[@"type"];
        NSDictionary *contentDict = item[@"content"];
        if ([@"id_card_portrait_side" isEqualToString:type]) {
            IdCardItem *idcardItem = [[IdCardItem alloc] init];
            idcardItem.name = contentDict[@"name"];
            idcardItem.sex = contentDict[@"sex"];
            idcardItem.ethnicity = contentDict[@"ethnicity"];
            idcardItem.birth = contentDict[@"birth"];
            idcardItem.address = contentDict[@"address"];
            idcardItem.number = contentDict[@"number"];
        } else if ([@"vat_invoice" isEqualToString:type]) {
            VatInvoiceItem *vatItem = [[VatInvoiceItem alloc] init];
            vatItem.itemtype = contentDict[@"type"];
            vatItem.serial_number = contentDict[@"serial_number"];
            vatItem.attribution = contentDict[@"attribution"];
            vatItem.code = contentDict[@"code"];
            vatItem.check_code = contentDict[@"check_code"];
            vatItem.machine_number = contentDict[@"machine_number"];
            vatItem.print_number = contentDict[@"print_number"];
            vatItem.number = contentDict[@"number"];
            vatItem.issue_date = contentDict[@"issue_date"];
            vatItem.encryption_block = contentDict[@"encryption_block"];
            vatItem.buyer_name = contentDict[@"buyer_name"];
            vatItem.buyer_id = contentDict[@"buyer_id"];
            vatItem.buyer_address = contentDict[@"buyer_address"];
            vatItem.buyer_bank = contentDict[@"buyer_bank"];
            vatItem.seller_name = contentDict[@"seller_name"];
            vatItem.seller_id = contentDict[@"seller_id"];
            vatItem.seller_address = contentDict[@"seller_address"];
            vatItem.seller_bank = contentDict[@"seller_bank"];
            vatItem.subtotal_amount = contentDict[@"subtotal_amount"];
            vatItem.subtotal_tax = contentDict[@"subtotal_tax"];
            vatItem.total = contentDict[@"total"];
            vatItem.total_in_words = contentDict[@"total_in_words"];
            vatItem.remarks = contentDict[@"remarks"];
            vatItem.receiver = contentDict[@"receiver"];
            vatItem.reviewer = contentDict[@"reviewer"];
            vatItem.issuer = contentDict[@"issuer"];

            vatItem.supervision_seal = contentDict[@"supervision_seal"];
            vatItem.seller_seal = contentDict[@"seller_seal"];
            vatItem.item_list = contentDict[@"item_list"];

            NSLog(@"itemtype = %@\nserial_number = %@\nattribution= %@", vatItem.itemtype, vatItem.seller_seal, vatItem.attribution);
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
